package com.umeng.community.example.Utils;

import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.support.v4.app.NotificationCompat;
import android.widget.RemoteViews;

import com.android.volley.Request.Method;
import com.android.volley.RequestQueue;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.qianxx.base.AppManager;
import com.qianxx.base.Urls;
import com.qianxx.base.utils.LogUtil;
import com.qianxx.draw.R;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;

public final class UpgradeManager {

	private static UpgradeManager instance = new UpgradeManager();

	private UpgradeManager() {
	}

	public static UpgradeManager getInstance() {
		return instance;
	}

	private static final String UPGRADE_APK_PATH = Environment
			.getExternalStorageDirectory() + "/draw/童话秀秀.apk";

	private RemoteViews mViews;
	private NotificationManager mNotifyMgr;
	private Notification mNotify;
	private int length;
	private Context mContext;

	private int getCurrVersion() {
		PackageManager pm = mContext.getPackageManager();
		try {
			PackageInfo info = pm.getPackageInfo(mContext.getPackageName(), 0);
			return info.versionCode;
		} catch (NameNotFoundException e) {
		}
		return 0;
	}

	private String getCurrVersionName() {
		PackageManager pm = mContext.getPackageManager();
		try {
			PackageInfo info = pm.getPackageInfo(mContext.getPackageName(), 0);
			return info.versionName;
		} catch (NameNotFoundException e) {
		}
		return "";
	}

	private boolean isFirst;

	public void setIsFirst(boolean isFirst) {
		this.isFirst = isFirst;
	}

	public void checkUpgrade(Context context) {
		LogUtil.d("执行checkUpgrade");
		mContext = context;
		RequestQueue queue = Volley.newRequestQueue(mContext);
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("platform", "android");
		map.put("versionNo", "" + getCurrVersion());
		map.put("versionName", getCurrVersionName());
		String url = UrlUtils.getURL(Urls.VERSION_URL, map);
		LogUtil.d("url: " + url);
		StringRequest request = new StringRequest(Method.GET, url, listener,
				errorListener);
		queue.add(request);
	}

	private Listener<String> listener = new Listener<String>() {
		@Override
		public void onResponse(String response) {
			LogUtil.d("response=" + response);
			// 对返回的数据进行处理
			try {
				JSONObject object = new JSONObject(response);
				int code = object.getInt("errCode");
				if (code != 0) {
					String msg = object.getString("message");
					// ToastUtil.getInstance().toast(msg);
					// 出现异常
					LogUtil.e("UpgradeManager：" + msg);
					return;
				}
				String result = object.getString("data");
				JSONObject rObject = new JSONObject(result);
				boolean update = rObject.getBoolean("update");
				if (!update) {
					// 已是最新版本
					LogUtil.d("已是最新版本");
					return;
				}

				boolean isUsed = rObject.getBoolean("isUsed");
				if (isUsed) {
					if (!isFirst) {
						// 非强制升级版本，不重复弹出提示
						LogUtil.d("非强制升级版本，不重复弹出提示");
						return;
					}
				}
				isFirst = false;
				parse(rObject, isUsed);

			} catch (JSONException e) {
				e.printStackTrace();
			}

		}
	};

	private String apkurl;

	private void parse(JSONObject info, boolean isUsed) {
		try {
			apkurl = info.getString("updUrl");
			length = (int) (info.getDouble("fileSize")) * 1024;
			String content = info.getString("updContent");
			// 对话框提示新版本
			if (isUsed) {
				new AlertDialog.Builder(mContext)
						.setTitle("软件版本更新")
						.setMessage(content)
						.setPositiveButton("后台下载",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
										upgrade(apkurl);
									}
								}).setNegativeButton("以后再说", null)
						.setCancelable(false).show();
			} else {
				new AlertDialog.Builder(mContext)
						.setTitle("软件版本更新")
						.setMessage(content)
						.setPositiveButton("后台下载",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
										upgrade(apkurl);
										AppManager.getAppManager()
												.finishAllActivity();
									}
								}).setCancelable(false).show();
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	private ErrorListener errorListener = new ErrorListener() {
		@Override
		public void onErrorResponse(VolleyError error) {
			LogUtil.w("请求失败");
		}
	};

	private void upgrade(String apkurl) {
		new UpgradTask().execute(apkurl);
	}

	class UpgradTask extends AsyncTask<String, Integer, String> {
		@Override
		protected void onPreExecute() {
			showNotify();
		}

		protected String doInBackground(String... params) {
			FileOutputStream fos = null;
			InputStream is = null;
			try {
				URL url = new URL(params[0]);
				HttpURLConnection conn = (HttpURLConnection) url
						.openConnection();
				// 设置超时时间
				conn.setConnectTimeout(25000);
				conn.setReadTimeout(25000);
				int responseCode = conn.getResponseCode();
				if (responseCode != HttpURLConnection.HTTP_OK) {
					return null;
				}
				is = conn.getInputStream();
				int len = 0;
				byte[] buffer = new byte[1024];
				File upgradeFile = new File(UPGRADE_APK_PATH);
				if (!upgradeFile.exists()) {
					// 如果文件不存在，说明是第一次升级，
					// 需要先创建文件夹
					upgradeFile.getParentFile().mkdirs();
				}
				fos = new FileOutputStream(UPGRADE_APK_PATH);
				int loaded = 0;// 已下载大小
				int times = 0;
				while (-1 != (len = is.read(buffer))) {
					loaded += len;
					fos.write(buffer, 0, len);
					// 每下载8%更新一次通知
					if (loaded * 100 / length >= 8 * times) {
						times++;
						publishProgress(loaded);
					}
				}
				completeNotify();
			} catch (MalformedURLException e) {
			} catch (IOException e) {
			} finally {
				if (is != null) {
					try {
						is.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				if (fos != null) {
					try {
						fos.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}

			return null;
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			updateNotify(values[0]);
		}

		@Override
		protected void onPostExecute(String result) {
			finishNotify();
			Intent intent = new Intent(Intent.ACTION_VIEW);
			intent.setDataAndType(Uri.fromFile(new File(UPGRADE_APK_PATH)),
					"application/vnd.android.package-archive");
			mContext.startActivity(intent);
		}

	}

	private void completeNotify() {
		mViews.setProgressBar(R.id.progressBar1, 100, 100, false);
		mViews.setTextViewText(R.id.textView1, 100 + "%");
		mViews.setTextViewText(R.id.textView2, "已完成下载");
		mNotifyMgr.notify(12345, mNotify);
	}

	private void updateNotify(int progress) {
		int n = progress * 100 / length;
		mViews.setProgressBar(R.id.progressBar1, length, progress, false);
		mViews.setTextViewText(R.id.textView1, n + "%");
		mViews.setTextViewText(R.id.textView2, "正在下载最新版本");
		mNotifyMgr.notify(12345, mNotify);
	}

	private void finishNotify() {
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setDataAndType(Uri.fromFile(new File(UPGRADE_APK_PATH)),
				"application/vnd.android.package-archive");
		PendingIntent contentIntent = PendingIntent.getActivity(mContext, 0,
				intent, 0);
		mNotify.contentIntent = contentIntent;
		mNotify.flags = Notification.FLAG_AUTO_CANCEL;
		mNotifyMgr.notify(12345, mNotify);
	}

	private void showNotify() {
		mNotifyMgr = (NotificationManager) mContext
				.getSystemService(Context.NOTIFICATION_SERVICE);
		mViews = new RemoteViews(mContext.getPackageName(),
				R.layout.custom_notification);
		mNotify = new NotificationCompat.Builder(mContext)
				.setSmallIcon(R.drawable.app_icon).setTicker("下载新版本")
				.setWhen(System.currentTimeMillis()).setContent(mViews).build();
		mNotify.flags = Notification.FLAG_NO_CLEAR;
		mNotifyMgr.notify(12345, mNotify);
	}

}
